package com.seeyon.apps.cxgd.service.tc;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.seeyon.apps.cxgd.entity.ResountEntity;
import com.seeyon.apps.cxgd.kit.DBKit;
import com.seeyon.apps.cxgd.kit.FormCap4Kit;
import com.seeyon.apps.cxgd.kit.LogKit;
import com.seeyon.apps.cxgd.kit.StrKit;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.cap4.form.bean.FormFieldBean;
import com.seeyon.cap4.form.bean.FormTableBean;
import com.seeyon.cap4.form.modules.engin.base.formData.CAP4FormDataManager;
import com.seeyon.cap4.form.service.CAP4FormManager;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.po.ctpenumnew.CtpEnumItem;
import com.seeyon.ctp.organization.bo.V3xOrgEntity;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.manager.OrgManager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.sql.SQLException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 酒店回推数据Service
 */
public class JDOrderService {
    private static Log log = LogFactory.getLog(JDOrderService.class);
    private CAP4FormManager cap4FormManager = (CAP4FormManager) AppContext.getBean("cap4FormManager");
    private CAP4FormDataManager cap4FormDataManager = (CAP4FormDataManager)AppContext.getBean("cap4FormDataManager");

    private OrgManager orgManager = (OrgManager)AppContext.getBean("orgManager");

    private final static String JD_NUMBER = "JD_DT001";


    /**
     *
     * @param notifyData
     * @param subNotifyType
     * @return
     * @throws Exception
     */
    public ResountEntity JdOrder(String notifyData, String subNotifyType) throws Exception {
        log.info("推送酒店订单数据："+notifyData);
        Map<String,Object> dataMap = null;
        //获取订单详情
        Map<String,Object> orderDetailsMap = null;
        //获取订单号
        String orderSerialNo = "";
        try{
            JSONObject jsonObject = JSON.parseObject(notifyData);
            dataMap = JSONObject.parseObject(JSONObject.toJSONString(jsonObject.get("data")),Map.class);
            orderDetailsMap = JSONObject.parseObject(JSONObject.toJSONString(dataMap.get("orderInfo")),Map.class);
            orderSerialNo = StrKit.str(orderDetailsMap.get("orderSerialNo"));
        }catch (Exception e){
            log.info("解析同城回退订单-火车数据异常！",e);
        }

        LogKit.addLog("同程回退订单-酒店【订单号："+orderSerialNo+"】", "同程回退订单-酒店【订单号："+orderSerialNo+"】", notifyData, "subNotifyType状态："+subNotifyType);
        String JD_NUMBER = "TCHDDXX_001";
        DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        //获取同步差旅信息
        FormBean cggcsFormBean = cap4FormManager.getFormByFormCode(JD_NUMBER);
        String tableName = cggcsFormBean.getMasterTableBean().getTableName();
        FormFieldBean yddhField = cggcsFormBean.getFieldBeanByDisplay("原订单号");
        FormFieldBean ccrField = cggcsFormBean.getFieldBeanByDisplay("出差人");
        FormFieldBean ddztField = cggcsFormBean.getFieldBeanByDisplay("订单状态");

        //获取退款信息
        Map<String,Object> refundMap = JSONObject.parseObject(JSONObject.toJSONString(dataMap.get("refundInfo")),Map.class);

        //获取人员组Id
        String outEmployeeIdZ = StrKit.str(orderDetailsMap.get("outEmployeeId"));
        //获取人员信息
        List<Map<String,Object>> residentList = JSONObject.parseObject(JSONObject.toJSONString(dataMap.get("residentList")),List.class);
        //获取房间信息
        List<Map<String,Object>> roomList = JSONObject.parseObject(JSONObject.toJSONString(dataMap.get("roomList")),List.class);
        //保存表单数据集合
        List<HashMap<String,Object>> maps = new ArrayList<>();
        for (Map<String, Object> map : residentList) {
            //房间单号
            String productOrderSerialNo = StrKit.str(map.get("productOrderSerialNo"));
            //获取对应人员房间信息
            Map<String, Object> roomMap = roomList.stream().filter(r -> StrKit.str(r.get("productOrderSerialNo")).equals(productOrderSerialNo)).collect(Collectors.toList()).get(0);
            //获取状态
            String orderStatusText = StrKit.str(roomMap.get("orderStatusDesc"));
            //变更前子订单号
            String previousProductOrderSerialNo = StrKit.str(roomMap.get("previousProductOrderSerialNo"));
            //外部员工id
            String outEmployeeId = StrKit.str(map.get("outEmployeeId"));
            //票价
            String price = StrKit.str(roomMap.get("companyPrice"));
            //手续费
            String refundFee = "";
            //差旅单号
            String travelApplyNo = StrKit.str(map.get("travelApplyNo"));
            //入住时间
            String departTime = StrKit.str(roomMap.get("checkInDate"));
            LocalDateTime departDateTime = LocalDateTime.parse(departTime, inputFormatter);
            departTime = departDateTime.format(outputFormatter);
            //离店时间
            String arriveTime = StrKit.str(roomMap.get("checkOutDate"));
            LocalDateTime arriveDateTime = LocalDateTime.parse(arriveTime, inputFormatter);
            arriveTime = arriveDateTime.format(outputFormatter);
            V3xOrgMember member = null;
            try {
                member = orgManager.getMemberById(Long.valueOf(outEmployeeId));
            } catch (BusinessException e) {
                log.info("机票订单-根据外部人员获取人员Id 异常！", e);
            }
            //变更逻辑，如果订单状态【orderStatusDesc】为已退款，则根据房间子订单号【productOrderSerialNo】获取退款信息中的数据。
            // 如果订单状态【orderStatusDesc】为待入住，则根据子订单号【previousProductOrderSerialNo】获取退款信息中的数据。
            if(orderStatusText.equals("已退款")){
                List<Map<String,Object>> refundInfoList = JSONObject.parseObject(JSONObject.toJSONString(refundMap.get("refundInfoList")),List.class);
                for (Map<String, Object> stringObjectMap : refundInfoList) {
                    List<Map<String,Object>> refundProductOrderInfo = JSONObject.parseObject(JSONObject.toJSONString(stringObjectMap.get("refundProductOrderInfo")),List.class);
                    for (Map<String, Object> objectMap : refundProductOrderInfo) {
                        if(StrKit.str(objectMap.get("productOrderSerialNo")).equals(productOrderSerialNo)){
                            price = StrKit.str(objectMap.get("refundAmout"));
                            if(!price.contains("-")){
                                price = "-"+price;
                            }
                            refundFee = StrKit.str(objectMap.get("refundFee"));
                        }
                    }
                }
            }else if(!previousProductOrderSerialNo.equals("")){
                List<Map<String,Object>> refundInfoList = JSONObject.parseObject(JSONObject.toJSONString(refundMap.get("refundInfoList")),List.class);
                for (Map<String, Object> stringObjectMap : refundInfoList) {
                    List<Map<String,Object>> refundProductOrderInfo = JSONObject.parseObject(JSONObject.toJSONString(stringObjectMap.get("refundProductOrderInfo")),List.class);
                    for (Map<String, Object> objectMap : refundProductOrderInfo) {
                        if(StrKit.str(objectMap.get("productOrderSerialNo")).equals(previousProductOrderSerialNo)){
                            //获取需要回写的字段信息
                            HashMap<String, Object> hcMap = new HashMap<>();
                            hcMap.put("出差人工号",member != null?member.getCode():"");
                            hcMap.put("出差人",member != null?member.getId():"");
                            hcMap.put("出差申请单号",travelApplyNo);
                            hcMap.put("订单类型","酒店订单");
                            hcMap.put("订单状态","已退款");
                            String refundAmout = StrKit.str(objectMap.get("refundAmout"));
                            if(!refundAmout.contains("-")){
                                refundAmout = "-"+refundAmout;
                            }
                            hcMap.put("价格",refundAmout);

                            hcMap.put("出发入住日期","");
                            hcMap.put("到达离开日期","");
                            hcMap.put("出发地","");
                            hcMap.put("目的地","");
                            hcMap.put("同程单号",orderSerialNo);
                            hcMap.put("上车地点","");
                            hcMap.put("下车地点","");
                            hcMap.put("原订单号",StrKit.str(objectMap.get("productOrderSerialNo")));
                            hcMap.put("手续费",StrKit.str(objectMap.get("refundFee")));
                            hcMap.put("子订单号","");

                            //组装主表和明细表数据map
                            HashMap<String,Object> mapData = new HashMap<>();
                            mapData.put("masterData",hcMap);
                            mapData.put("mxData",null);
                            maps.add(mapData);
                        }
                    }
                }
            }
            //根据订单信息是否存在档案表中,如果存在就不回写档案表中
            String sql = "select id from "+tableName+" where "+yddhField.getName()+" = '"+productOrderSerialNo+"' and "+ccrField.getName()+" = '"+outEmployeeId+"' and "+ddztField.getName()+" = '"+orderStatusText+"'";
            List<Map<String, Object>> maps1 = DBKit.excuteSQL(sql, null);
            if(maps1.isEmpty()){
                //获取需要回写的字段信息
                HashMap<String, Object> hcMap = new HashMap<>();
                hcMap.put("出差人工号",member != null?member.getCode():"");
                hcMap.put("出差人",member != null?member.getId():"");
                hcMap.put("出差申请单号",travelApplyNo);
                hcMap.put("订单类型","酒店订单");
                hcMap.put("订单状态",orderStatusText);
                hcMap.put("价格",price);

                hcMap.put("出发入住日期",departTime);
                hcMap.put("到达离开日期",arriveTime);
                hcMap.put("出发地","");
                hcMap.put("目的地","");
                hcMap.put("同程单号",orderSerialNo);
                hcMap.put("上车地点","");
                hcMap.put("下车地点","");
                hcMap.put("原订单号",productOrderSerialNo);
                hcMap.put("手续费",refundFee);
                hcMap.put("子订单号",previousProductOrderSerialNo);

                //组装主表和明细表数据map
                HashMap<String,Object> mapData = new HashMap<>();
                mapData.put("masterData",hcMap);
                mapData.put("mxData",null);
                maps.add(mapData);
            }
        }
        if(!maps.isEmpty()){
            try {
                if(!outEmployeeIdZ.equals("")){
                    V3xOrgMember orgMember = orgManager.getMemberById(Long.valueOf(outEmployeeIdZ));
                    if(orgMember == null){
                        log.info("获取人员【"+outEmployeeIdZ+"】异常！");
                        return new ResountEntity(true,"1","回写酒店订单失败");
                    }
                    FormCap4Kit.saveCAP4FormData(orgMember,JD_NUMBER,maps,false);
                }else{
                    log.info("获取组负责人【"+outEmployeeIdZ+"】为空！");
                }
            } catch (Exception e) {
                log.info("添加酒店数据失败：",e);
            }
        }
        return new ResountEntity(true,"100","回写酒店订单成功");
    }


    /**
     * 切换订单子类型
     * 1:确认中 2:待入住 3:已退房 4:已取消 5:预定失败 6:已变更
     * 说明：
     * 1：确认中，提交酒店订单后，未确认之前的中间状态节点
     * 2：待入住，提交酒店订单后，已确认待入住的状态
     * 3：已退房，提交酒店订单后，未确认被拒单/已确认后取消订单取消成功
     * 4：已取消，提交酒店订单前，取消成功
     * 6：已变更，申请延迟入住、提前离店、部分退房，变更完成
     * 7：变更驳回
     * 8：退房驳回
     * 9：取消驳回
     * @return
     */
    private String getSubNotifyType(String subNotifyType){
        if(subNotifyType.equals("1")){
            subNotifyType = "确认中";
        }else if(subNotifyType.equals("2")){
            subNotifyType = "待入住";
        }else if(subNotifyType.equals("3")){
            subNotifyType = "已退房";
        }else if(subNotifyType.equals("4")){
            subNotifyType = "已取消";
        }else if(subNotifyType.equals("5")){
            subNotifyType = "预定失败";
        }else if(subNotifyType.equals("6")){
            subNotifyType = "已变更";
        }else if(subNotifyType.equals("7")){
            subNotifyType = "变更驳回";
        }else if(subNotifyType.equals("8")){
            subNotifyType = "退房驳回";
        }else if(subNotifyType.equals("9")){
            subNotifyType = "取消驳回";
        }
        return subNotifyType;
    }


    /**
     * 给主表
     * @param masterId
     * @param formBean
     * @param filedName
     * @param fieldValue
     * @throws BusinessException
     * @throws SQLException
     */
    private void updateWuxiao(Long masterId,FormBean formBean,String filedName,String fieldValue) throws BusinessException, SQLException {
        FormDataMasterBean dataMasterBean = cap4FormManager.findDataById(masterId, formBean, null);
        dataMasterBean.addFieldValue(filedName,fieldValue);
        cap4FormDataManager.insertOrUpdateMasterData(dataMasterBean);
    }



    //订单状态转换
    private String getOrderStatus(int status){
        String statusString = "";
        switch (status){
            case 1:
                statusString = "确认中";
                break;
            case 2:
                statusString = "待入住";
                break;
            case 3:
                statusString = "已退房";
                break;
            case 4:
                statusString = "已取消";
                break;
            case 5:
                statusString = "待提交";
                break;
            case 6:
                statusString = "待审批";
                break;
            case 7:
                statusString = "待支付";
                break;
            case 8:
                statusString = "退房中";
                break;
            case 9:
                statusString = "已入住";
                break;
            case 10:
                statusString = "已离店";
                break;
        }
        return statusString;
    }
}
